<?php
/**
 * Description: 公开课推广页面
 * User: devforma
 * Date: 15/6/29
 * Time: 12:48
 */

class PromoteOpenClass implements iController {
    private $pcUrl, $pcOverdueUrl, $mobileUrl;

    public function __construct() {
        $this->pcUrl = 'http://promote.yaoguo.cn/index.php?course_id=%id&src=%src';
        $this->pcOverdueUrl = 'http://promote.yaoguo.cn/course.php?course_id=%id&src=%src';
        $this->mobileUrl = YG_MOBILE_SECURE_URL . '/promote/index.html#/index/class?course_id=%id&src=%src';
    }

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;
        if (!empty($queryArgs['course_id']) && is_numeric($queryArgs['course_id'])) {
            $courseId = intval($queryArgs['course_id']);
            $cacheKey = 'exist_opencourse:'.$courseId;

            $existList = cacheGet($cacheKey);
            if (!is_array($existList))
                $existList = array();

            if (!isset($existList[$courseId])) {
                $sql = 'SELECT cl.start_time FROM `data_live_course` AS co, `relationship_live_class_and_course` AS r, `data_live_class` AS cl
                WHERE co.id=:cid AND co.id=r.course_id AND r.class_id=cl.id AND co.type_id=1 LIMIT 1';
                $startTime = $cmsdb->getVar($sql, array(':cid' => $courseId));

                if ($startTime) {
                    $existList[$courseId] = $startTime;
                    cacheSet($cacheKey, $existList, 3600);
                    $this->redirect($courseId, $startTime);
                }

            } else {
                $this->redirect($courseId, $existList[$courseId]);
            }
        }

        die('非法访问');
    }

    /**
     * 重定向跳转
     * @param int $courseId 课程id
     * @param string $startTime 课堂开始时间
     */
    private function redirect($courseId, $startTime) {
        $isOverdue = (time() - strtotime($startTime)) > 7*24*60*60; //7天过期

        $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $referer = strtolower($_SERVER['HTTP_REFERER']);

        if (preg_match('/android|iphone|phone|mobile/', $userAgent)) { //手机访问
            $url = $this->mobileUrl;
        } else { //PC访问
            $url = $isOverdue ? $this->pcOverdueUrl : $this->pcUrl;
        }

        if (strpos($userAgent, 'weibo') !== false || strpos($referer, 'weibo.com') !== false)
            $src = 'weibo';
        elseif (strpos($referer, 'baidu.com') !== false || strpos($referer, 'promote.php') !== false)
            $src = 'baidu';
        else
            $src = 'other';

        $url = str_replace(array('%id', '%src'), array($courseId, $src), $url);

        header('Location: ' . $url);
        exit();
    }
}